package com.wxy.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.rabbitmq.client.Channel;
import com.wxy.dao.UserMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.amqp.RabbitProperties;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.lang.model.element.NestingKind;
import java.io.IOException;
import java.security.Key;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author 47868
 */
@Service
public class RabbitMQService {
    @Autowired
    private UserService userService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    private final ObjectMapper objectMapper;
    private static AtomicInteger num=new AtomicInteger(1);
    @Autowired
    public RabbitMQService(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }
    @RabbitListener(queues = "wxy.queue1")
    public void process(Map<String,Object> map) {
        userService.updateById((int)map.get("id"),(String)map.get("password"));
    }

    @RabbitListener(queues = "wxy.queue2")
    public void process2(Message message, Channel channel) {
            Long deliveryTag = message.getMessageProperties().getDeliveryTag();
            try {
                byte[] bytes=message.getBody();
                Map map =objectMapper.readValue(bytes,Map.class);
                String id=map.get("id").toString();
                channel.basicAck(deliveryTag,false);
                System.err.println("queue2..."+id);
            }
            catch (Exception e) {
                throw new RuntimeException(e);
                /*e.printStackTrace();
                try {
                    channel.basicNack(deliveryTag,false,true);
                    System.err.println("queue2..."+e.getMessage());
                }
                catch (IOException e1) {
                    e1.printStackTrace();
                }*/
            }
    }

    @RabbitListener(queues = "wxy.queue3")
    public void process3(String message) {
        System.out.println("queue3..."+message);
    }
    //使用注解方式创建并绑定队列
    /*@RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "wxy.queue4"),
            exchange = @Exchange(value = "amq.direct", type = ExchangeTypes.DIRECT),
            key={"red","blue"}))
    public void process4(String message){
        System.out.println("queue4.."+message);
    }*/
}
